<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <link rel="icon" href="favicon.ico" type="image/x-icon">
      <title>贪吃蛇游戏</title>
    <style>
        *
          {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Arial Rounded MT Bold', 'Microsoft YaHei', sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            background: linear-gradient(135deg, #1a2a6c, #2c3e50);
            color: #fff;
            padding: 20px;
            overflow-x: hidden;
        }
        
        .header {
            text-align: center;
            margin-bottom: 20px;
            width: 100%;
        }
        
        h1 {
            font-size: 2.8rem;
            margin-bottom: 10px;
            text-shadow: 0 0 10px rgba(0, 255, 150, 0.7);
            letter-spacing: 2px;
        }
        
        .game-info {
            display: flex;
            justify-content: space-between;
            width: 100%;
            max-width: 450px;
            margin-bottom: 15px;
            background: rgba(0, 0, 0, 0.3);
            padding: 10px 20px;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
        }
        
        .score-container, .high-score-container {
            font-size: 1.3rem;
            font-weight: bold;
        }
        
        #score, #high-score {
            color: #ffcc00;
            font-size: 1.5rem;
        }
        
        .game-container {
            position: relative;
            margin-bottom: 20px;
        }
        
        canvas {
            border: 3px solid #4CAF50;
            border-radius: 8px;
            box-shadow: 0 0 20px rgba(76, 175, 80, 0.6);
            background-size: 20px;
            touch-action: none;
        }
        
        .controls {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-top: 15px;
        }
        
        .direction-buttons {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            grid-template-rows: repeat(3, 1fr);
            gap: 10px;
            margin-top: 10px;
        }
        
        .control-btn {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.2);
            border: 2px solid rgba(255, 255, 255, 0.3);
            color: white;
            font-size: 1.5rem;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.2s ease;
            user-select: none;
        }
        
        .control-btn:active {
            background: rgba(76, 175, 80, 0.8);
            transform: scale(0.95);
        }
        
        .up-btn { grid-column: 2; grid-row: 1; }
        .left-btn { grid-column: 1; grid-row: 2; }
        .right-btn { grid-column: 3; grid-row: 2; }
        .down-btn { grid-column: 2; grid-row: 3; }
        
        .game-buttons {
            display: flex;
            gap: 15px;
            margin-top: 20px;
            margin-bottom: 30px;
        }
        
        .game-btn {
            padding: 12px 25px;
            font-size: 1.1rem;
            font-weight: bold;
            border: none;
            border-radius: 50px;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
        }
        
        #start-btn {
            background: linear-gradient(to right, #4CAF50, #2E7D32);
            color: white;
        }
        
        #pause-btn {
            background: linear-gradient(to right, #FF9800, #EF6C00);
            color: white;
        }
        
        #restart-btn {
            background: linear-gradient(to right, #2196F3, #0D47A1);
            color: white;
        }
        
        .game-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.3);
        }
        
        .instructions {
            max-width: 500px;
            margin-top: 20px;
            padding: 15px;
            background: rgba(0, 0, 0, 0.3);
            border-radius: 10px;
            font-size: 0.95rem;
            line-height: 1.6;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            overflow-y: auto;
            max-height: 150px;
        }
        
        .food-info {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-top: 15px;
        }
        
        .food-item {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .food-img {
            width: 24px;
            height: 24px;
            background-size: contain;
            background-repeat: no-repeat;
        }
        
        .mobile-controls {
            display: none;
        }
        
        @media (max-width: 768px) {
            .mobile-controls {
                display: block;
            }
            
            .control-btn {
                width: 70px;
                height: 70px;
                font-size: 2rem;
            }
            
            h1 {
                font-size: 2.3rem;
            }
        }
        
        @media (max-width: 480px) {
            canvas {
                width: 300px;
                height: 300px;
            }
            
            .control-btn {
                width: 55px;
                height: 55px;
                font-size: 1.5rem;
            }
            
            .game-info {
                flex-direction: column;
                align-items: center;
                gap: 8px;
            }
        }
        
        .game-over {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.85);
            display: none;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            border-radius: 8px;
            z-index: 10;
        }
        
        .game-over h2 {
            font-size: 3rem;
            color: #ff5252;
            margin-bottom: 20px;
            text-shadow: 0 0 10px rgba(255, 82, 82, 0.7);
        }
        
        .game-over p {
            font-size: 1.8rem;
            margin-bottom: 30px;
            color: #ffcc00;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>贪吃蛇大冒险</h1>
    </div>
    
    <div class="game-info">
        <div class="score-container">分数: <span id="score">0</span></div>
        <div class="high-score-container">最高分: <span id="high-score">0</span></div>
    </div>
    
    <div class="game-container">
        <canvas id="gameCanvas" width="450" height="450"></canvas>
        <div class="game-over" id="game-over">
            <h2>游戏结束!</h2>
            <p>得分: <span id="final-score">0</span></p>
            <button class="game-btn" id="restart-btn">重新开始</button>
        </div>
    </div>
    
    <div class="food-info">
        <div class="food-item">
            <div class="food-img" style="background-image: url('apple.png')"></div>
            <span>食物1 (1分)</span>
        </div>
        <div class="food-item">
            <div class="food-img" style="background-image: url('gold_apple.png')"></div>
            <span>食物2 (5分)</span>
        </div>
    </div>
    
    <div class="game-buttons">
        <button class="game-btn" id="start-btn">开始游戏</button>
        <button class="game-btn" id="pause-btn">暂停游戏</button>
    </div>
    
    <div class="mobile-controls">
        <p>方向控制:</p>
        <div class="direction-buttons">
            <div class="control-btn up-btn" id="up-btn">↑</div>
            <div class="control-btn left-btn" id="left-btn">←</div>
            <div class="control-btn right-btn" id="right-btn">→</div>
            <div class="control-btn down-btn" id="down-btn">↓</div>
        </div>
    </div>
    
    <div class="instructions">
        <p><strong>游戏说明:</strong> 使用键盘方向键、鼠标在游戏区域滑动或屏幕上的方向按钮控制蛇的移动。吃到食物1得1分，食物2得5分。撞到墙壁或自己的身体游戏结束！</p>
        <p><strong>控制方式:</strong></p>
        <p>- 电脑: 键盘方向键或鼠标在游戏区内滑动</p>
        <p>- 手机: 屏幕上的方向按钮或在游戏区内滑动</p>
        <p><strong>注意:</strong> 暂停/继续功能通过按钮控制，空格键也可暂停/继续</p>
    </div>
    
    <script>
        // 游戏常量
        const GRID_SIZE = 15;
        const BOX_SIZE = 30;
        const FOOD1_PROBABILITY = 0.9;
        const FOOD2_PROBABILITY = 0.1;
        const BASE_GAME_SPEED = 300;
        
        // 游戏变量
        let canvas, ctx;
        let snake = [];
        let food = {};
        let direction = 'right';
        let nextDirection = 'right';
        let gameInterval;
        let score = 0;
        let highScore = localStorage.getItem('snakeHighScore') || 0;
        let gameRunning = false;
        let gamePaused = false;
        let gameSpeed = BASE_GAME_SPEED;
        let speedLevel = 0;
        
        // 图片资源
        let snakeHeadImg, snakeBodyImg, food1Img, food2Img;
        
        // 加载图片
        function loadImages() {
            snakeHeadImg = new Image();
            snakeHeadImg.src = 'head.png';
            
            snakeBodyImg = new Image();
            snakeBodyImg.src = 'body.png';
            
            food1Img = new Image();
            food1Img.src = 'apple.png';
            
            food2Img = new Image();
            food2Img.src = 'gold_apple.png';
        }
        
        // 初始化游戏
        function initGame() {
            canvas = document.getElementById('gameCanvas');
            ctx = canvas.getContext('2d');
            
            canvas.width = GRID_SIZE * BOX_SIZE;
            canvas.height = GRID_SIZE * BOX_SIZE;
            
            loadImages();
            drawGrid();
            
            document.getElementById('high-score').textContent = highScore;
            initSnake();
            generateFood();
            drawGame();
        }
        
        // 绘制背景网格
        function drawGrid() {
            ctx.strokeStyle = 'rgba(255, 255, 255, 0.1)';
            ctx.lineWidth = 0.5;
            
            for (let x = 0; x <= canvas.width; x += BOX_SIZE) {
                ctx.beginPath();
                ctx.moveTo(x, 0);
                ctx.lineTo(x, canvas.height);
                ctx.stroke();
            }
            
            for (let y = 0; y <= canvas.height; y += BOX_SIZE) {
                ctx.beginPath();
                ctx.moveTo(0, y);
                ctx.lineTo(canvas.width, y);
                ctx.stroke();
            }
        }
        
        // 初始化蛇
        function initSnake() {
            snake = [];
            const startX = Math.floor(GRID_SIZE / 2);
            const startY = Math.floor(GRID_SIZE / 2);
            
            for (let i = 0; i < 3; i++) {
                snake.push({ x: startX - i, y: startY });
            }
            
            direction = 'right';
            nextDirection = 'right';
            speedLevel = 0;
            gameSpeed = BASE_GAME_SPEED;
        }
        
        // 生成食物
        function generateFood() {
            const foodType = Math.random() < FOOD2_PROBABILITY ? 2 : 1;
            
            let newFood;
            let onSnake;
            
            do {
                onSnake = false;
                newFood = {
                    x: Math.floor(Math.random() * GRID_SIZE),
                    y: Math.floor(Math.random() * GRID_SIZE),
                    type: foodType
                };
                
                for (let segment of snake) {
                    if (segment.x === newFood.x && segment.y === newFood.y) {
                        onSnake = true;
                        break;
                    }
                }
            } while (onSnake);
            
            food = newFood;
        }
        
        // 移动蛇
        function moveSnake() {
            if (gamePaused) return;
            
            direction = nextDirection;
            const head = { ...snake[0] };
            
            switch (direction) {
                case 'up': head.y -= 1; break;
                case 'down': head.y += 1; break;
                case 'left': head.x -= 1; break;
                case 'right': head.x += 1; break;
            }
            
            // 碰撞检测
            if (head.x < 0 || head.y < 0 || head.x >= GRID_SIZE || head.y >= GRID_SIZE) {
                gameOver();
                return;
            }
            
            for (let i = 0; i < snake.length; i++) {
                if (snake[i].x === head.x && snake[i].y === head.y) {
                    gameOver();
                    return;
                }
            }
            
            snake.unshift(head);
            
            // 吃到食物
            if (head.x === food.x && head.y === food.y) {
                score += food.type === 1 ? 1 : 5;
                document.getElementById('score').textContent = score;
                
                if (score > highScore) {
                    highScore = score;
                    localStorage.setItem('snakeHighScore', highScore);
                    document.getElementById('high-score').textContent = highScore;
                }
                
                generateFood();
            } else {
                snake.pop();
            }
        }
        
        // 绘制游戏
        function drawGame() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            drawGrid();
            
            // 绘制蛇
            for (let i = 0; i < snake.length; i++) {
                const segment = snake[i];
                
                if (i === 0) {
                    drawSnakeHead(segment);
                } else {
                    drawSnakeBody(segment);
                }
            }
            
            // 绘制食物
            drawFood();
        }
        
        // 绘制蛇头
        function drawSnakeHead(head) {
            ctx.save();
            
            let rotation = 0;
            switch (direction) {
                case 'up': rotation = 0; break;
                case 'right': rotation = Math.PI / 2; break;
                case 'down': rotation = Math.PI; break;
                case 'left': rotation = Math.PI * 1.5; break;
            }
            
            ctx.translate(
                head.x * BOX_SIZE + BOX_SIZE / 2, 
                head.y * BOX_SIZE + BOX_SIZE / 2
            );
            
            ctx.rotate(rotation);
            
            ctx.drawImage(
                snakeHeadImg, 
                -BOX_SIZE / 2, 
                -BOX_SIZE / 2, 
                BOX_SIZE, 
                BOX_SIZE
            );
            
            ctx.restore();
        }
        
        // 绘制蛇身
        function drawSnakeBody(segment) {
            ctx.drawImage(
                snakeBodyImg, 
                segment.x * BOX_SIZE, 
                segment.y * BOX_SIZE, 
                BOX_SIZE, 
                BOX_SIZE
            );
        }
        
        // 绘制食物
        function drawFood() {
            const img = food.type === 1 ? food1Img : food2Img;
            
            ctx.drawImage(
                img, 
                food.x * BOX_SIZE, 
                food.y * BOX_SIZE, 
                BOX_SIZE, 
                BOX_SIZE
            );
        }
        
        // 改变方向
        function changeDirection(newDirection) {
            if (
                (direction === 'up' && newDirection !== 'down') ||
                (direction === 'down' && newDirection !== 'up') ||
                (direction === 'left' && newDirection !== 'right') ||
                (direction === 'right' && newDirection !== 'left')
            ) {
                nextDirection = newDirection;
            }
        }
        
        // 开始游戏
        function startGame() {
            // 防止多次点击导致速度叠加
            if (gameRunning && !gamePaused) {
                // 增加速度级别
                speedLevel++;
                // 计算新速度（每次减少50ms，最低100ms）
                const newSpeed = Math.max(100, BASE_GAME_SPEED - (speedLevel * 50));
                
                // 只有速度有变化时才更新
                if (newSpeed !== gameSpeed) {
                    gameSpeed = newSpeed;
                    
                    // 重新设置游戏循环
                    clearInterval(gameInterval);
                    gameInterval = setInterval(gameLoop, gameSpeed);
                }
                return;
            }
            
            document.getElementById('game-over').style.display = 'none';
            
            if (!gameRunning) {
                score = 0;
                document.getElementById('score').textContent = score;
                document.getElementById('final-score').textContent = score;
                initSnake();
                generateFood();
                gameRunning = true;
                speedLevel = 0;
                gameSpeed = BASE_GAME_SPEED;
            }
            
            if (gamePaused) {
                gamePaused = false;
                document.getElementById('pause-btn').textContent = '暂停游戏';
            }
            
            // 清除现有循环并设置新循环
            if (gameInterval) {
                clearInterval(gameInterval);
            }
            gameInterval = setInterval(gameLoop, gameSpeed);
        }
        
        // 游戏主循环
        function gameLoop() {
            if (!gamePaused) {
                moveSnake();
                drawGame();
            }
        }
        
        // 暂停/继续游戏
        function togglePause() {
            if (!gameRunning) return;
            
            gamePaused = !gamePaused;
            
            if (gamePaused) {
                document.getElementById('pause-btn').textContent = '继续游戏';
            } else {
                document.getElementById('pause-btn').textContent = '暂停游戏';
            }
        }
        
        // 游戏结束
        function gameOver() {
            clearInterval(gameInterval);
            gameInterval = null;
            gameRunning = false;
            gamePaused = false;
            
            const gameOverScreen = document.getElementById('game-over');
            document.getElementById('final-score').textContent = score;
            gameOverScreen.style.display = 'flex';
        }
        
        // 重新开始游戏
        function restartGame() {
            clearInterval(gameInterval);
            gameInterval = null;
            gameRunning = false;
            gamePaused = false;
            startGame();
        }
        
        // 事件监听
        function setupEventListeners() {
            // 键盘控制
            document.addEventListener('keydown', (e) => {
                switch (e.key) {
                    case 'ArrowUp': changeDirection('up'); e.preventDefault(); break;
                    case 'ArrowDown': changeDirection('down'); e.preventDefault(); break;
                    case 'ArrowLeft': changeDirection('left'); e.preventDefault(); break;
                    case 'ArrowRight': changeDirection('right'); e.preventDefault(); break;
                    case ' ': if (gameRunning) togglePause(); e.preventDefault(); break;
                }
            });
            
            // 按钮事件
            document.getElementById('start-btn').addEventListener('click', startGame);
            document.getElementById('pause-btn').addEventListener('click', togglePause);
            document.getElementById('restart-btn').addEventListener('click', restartGame);
            
            // 触摸控制
            document.getElementById('up-btn').addEventListener('click', () => changeDirection('up'));
            document.getElementById('down-btn').addEventListener('click', () => changeDirection('down'));
            document.getElementById('left-btn').addEventListener('click', () => changeDirection('left'));
            document.getElementById('right-btn').addEventListener('click', () => changeDirection('right'));
            
            // 鼠标和触摸滑动控制
            setupSwipeControls();
        }
        
        // 设置滑动控制
        function setupSwipeControls() {
            let touchStartX = 0;
            let touchStartY = 0;
            let mouseDown = false;
            let lastMouseX = 0;
            let lastMouseY = 0;
            
            // 触摸开始
            canvas.addEventListener('touchstart', (e) => {
                touchStartX = e.touches[0].clientX;
                touchStartY = e.touches[0].clientY;
                e.preventDefault();
            }, { passive: false });
            
            // 触摸移动
            canvas.addEventListener('touchmove', (e) => {
                if (!touchStartX || !touchStartY) return;
                
                const touch = e.touches[0];
                const diffX = touch.clientX - touchStartX;
                const diffY = touch.clientY - touchStartY;
                
                if (Math.abs(diffX) > 10 || Math.abs(diffY) > 10) {
                    if (Math.abs(diffX) > Math.abs(diffY)) {
                        changeDirection(diffX > 0 ? 'right' : 'left');
                    } else {
                        changeDirection(diffY > 0 ? 'down' : 'up');
                    }
                    
                    touchStartX = touch.clientX;
                    touchStartY = touch.clientY;
                }
                
                e.preventDefault();
            }, { passive: false });
            
            // 触摸结束
            canvas.addEventListener('touchend', () => {
                touchStartX = 0;
                touchStartY = 0;
            });
            
            // 鼠标按下
            canvas.addEventListener('mousedown', (e) => {
                mouseDown = true;
                lastMouseX = e.clientX;
                lastMouseY = e.clientY;
                e.preventDefault();
            });
            
            // 鼠标移动
            canvas.addEventListener('mousemove', (e) => {
                if (mouseDown) {
                    const diffX = e.clientX - lastMouseX;
                    const diffY = e.clientY - lastMouseY;
                    
                    if (Math.abs(diffX) > 10 || Math.abs(diffY) > 10) {
                        if (Math.abs(diffX) > Math.abs(diffY)) {
                            changeDirection(diffX > 0 ? 'right' : 'left');
                        } else {
                            changeDirection(diffY > 0 ? 'down' : 'up');
                        }
                    }
                    
                    lastMouseX = e.clientX;
                    lastMouseY = e.clientY;
                    e.preventDefault();
                }
            });
            
            // 鼠标释放
            document.addEventListener('mouseup', () => {
                mouseDown = false;
            });
        }
        
        // 初始化游戏
        window.onload = function() {
            initGame();
            setupEventListeners();
        };
    </script>
</body>
</html>